package com.lesent.kafka.service.impl;

import com.lesent.kafka.Constant.Constant;
import com.lesent.kafka.common.JsonHelper;
import com.lesent.kafka.service.IKafkaService;
import net.bytebuddy.asm.Advice;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.ExecutionException;

/**
 * @author shengtao
 * @Description: kafka服务
 * @date 2018/12/19 16:22
 */
@Service
public class KafkaServiceImpl implements IKafkaService {

    @Autowired
    private Producer<String,String> kafkaProducer;
    @Autowired
    private KafkaConsumer<String,String> kafkaConsumer;

    @Override
    public <T> RecordMetadata send(String topic, String key, T t) throws ExecutionException, InterruptedException {
        if(StringUtils.isEmpty(topic)){
            topic = Constant.DEFAULT_TOPIC;
        }
        String value = JsonHelper.obj2Json(t);
        ProducerRecord<String,String> record = new ProducerRecord<String, String>(topic,key,value);
        RecordMetadata recordMetadata = kafkaProducer.send(record).get();
        return recordMetadata;
    }


}
